package com.jltx.xq.simplewatch.video.model.impl;

import android.text.TextUtils;

import com.jltx.xq.simplewatch.db.helper.NewsRecordDBHelper;
import com.jltx.xq.simplewatch.db.helper.NewsStateDBHelper;
import com.jltx.xq.simplewatch.news.api.TopicNewsApiService;
import com.jltx.xq.simplewatch.news.model.bean.NewsState;
import com.jltx.xq.simplewatch.news.model.bean.TopicNews;
import com.jltx.xq.simplewatch.news.model.bean.TopicNewsData;
import com.jltx.xq.simplewatch.news.model.bean.TopicNewsEntity;
import com.jltx.xq.simplewatch.news.model.bean.TopicNewsResponse;
import com.jltx.xq.simplewatch.news.model.bean.TopicNewsVideoResponse;
import com.jltx.xq.simplewatch.utils.GsonFactoryUtils;
import com.jltx.xq.simplewatch.utils.ListUtils;
import com.jltx.xq.simplewatch.utils.NewsStateUtils;
import com.jltx.xq.simplewatch.utils.PreUtils;
import com.jltx.xq.simplewatch.utils.VideoPathPraserUtils;
import com.jltx.xq.simplewatch.video.model.ITopicNetNewsModel;
import com.jltx.xq.simplewatch.video.model.ITopicNewsModel;

import java.util.ArrayList;
import java.util.List;

import cn.jltx.utils.XqLog;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2017/09/06.
 */

public class TopicNewsNetModelImpl implements ITopicNewsModel,ITopicNetNewsModel {
    private long lastTime;  //以s计
    private Integer lastMaxPageNewsRecord = null;  //缓存当前最大的页码

    @Override
    public Observable<TopicNewsEntity> getTopicNews(final String channel, boolean isDown) {
        lastTime = PreUtils.getLong(channel, 0);//读取对应频道下最后一次刷新的时间戳
        if (lastTime == 0) {
            //如果为空，则是从来没有刷新过，使用当前时间戳
            lastTime = System.currentTimeMillis() / 1000;
        }
        return TopicNewsApiService.getInstance().getTopicNewsApi().getTopicNews(channel, lastTime, System.currentTimeMillis() / 1000)
                .subscribeOn(Schedulers.io())
                .map(new Function<TopicNewsResponse, TopicNewsEntity>() {
                    @Override
                    public TopicNewsEntity apply(@NonNull TopicNewsResponse topicNewsResponse) throws Exception {
                        XqLog.d(TopicNewsModelImpl.TAG, "网络过来的新闻列表" + Thread.currentThread());
                        TopicNewsEntity topicNewsEntity = new TopicNewsEntity();
                        if (topicNewsResponse != null) {
                            List<TopicNewsData> data = topicNewsResponse.getData();
                            List<TopicNews> newsList = new ArrayList<>();
                            if (!ListUtils.isEmpty(data)) {
                                for (TopicNewsData newsData : data) {
                                    TopicNews topicNews = GsonFactoryUtils.providerGson().fromJson(newsData.getContent(), TopicNews.class);
                                    if(!TextUtils.isEmpty(topicNews.getTitle())){
                                        NewsState newsState = NewsStateDBHelper.getNewsState(channel, NewsStateUtils.convertTopicNewsStateKey(topicNews)); //key的规则:item_id/group_id/url
                                        if (newsState != null) {
                                            topicNews.setIsRead(newsState.getIs_read()); //设置到已经存在的新闻bean里面
                                            topicNews.setIsDel(newsState.getIs_del());
                                        }

                                        if(topicNews.getIsDel() == 0){
                                            newsList.add(topicNews);
                                        }
                                    }
                                }
                            }
                            topicNewsEntity.new_list = newsList;
                            topicNewsEntity.tips = topicNewsResponse.getTips();
                        }
                        return topicNewsEntity;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<TopicNewsEntity>() {
                    @Override
                    public void accept(@NonNull TopicNewsEntity topicNewsEntity) throws Exception {
                        setAndSaveLastTime(channel,System.currentTimeMillis() / 1000);
                    }
                });
    }

    @Override
    public void saveWeChatNews(String channel, int page, TopicNewsEntity topicNewsEntity) {
        //将最新页码的新闻列表保存到数据库
        NewsRecordDBHelper.saveNews(channel,page,(int)System.currentTimeMillis(),GsonFactoryUtils.providerGson().toJson(topicNewsEntity));
    }

    public void setAndSaveLastTime(String channel, long lastTime) {
        this.lastTime = lastTime;
        PreUtils.putLong(channel,lastTime);//保存刷新的时间戳
    }

    @Override
    public Observable<TopicNewsVideoResponse> getTopicNewsVideoPath(String srcUrl) {
        return Observable.create(new ObservableOnSubscribe<String[]>() {
            @Override
            public void subscribe(ObservableEmitter<String[]> e) throws Exception {
                String[] params = VideoPathPraserUtils.getVideoParseParam(srcUrl);
                e.onNext(params);
                e.onComplete();
            }
        })
                .subscribeOn(Schedulers.io()).flatMap(new Function<String[], ObservableSource<TopicNewsVideoResponse>>() {
                    @Override
                    public ObservableSource<TopicNewsVideoResponse> apply(@NonNull String[] strings) throws Exception {
                        String r = strings[0];
                        String s = strings[1];
                        return TopicNewsApiService.getInstance().getTopicNewsApi().getTopicNewsVideoPath(srcUrl, r, s);
                    }
                });
    }

    @Override
    public boolean isHadCacheNewsRecord() {
        return lastMaxPageNewsRecord != null;
    }

    public Integer getLastMaxPageNewsRecord() {
        return lastMaxPageNewsRecord == null ? 0 : lastMaxPageNewsRecord;
    }

    public void setLastMaxPageNewsRecord(Integer lastMaxPageNewsRecord) {
        this.lastMaxPageNewsRecord = lastMaxPageNewsRecord;
    }

}
